package com.blade.common.utils;

import java.util.*;

public class MapUtil {
    public static <T> Map<T, T> asMap(Class<? extends Map> clazz, T... t) {
        if (null == t) {
            t = (T[]) new Object[]{null};
        }

        try {
            Map map = clazz.newInstance();

            int len = t.length;

            for (int i = 0; i < len; i++) {
                map.put(t[i], i == len - 1 ? null : t[++i]);
            }

            return map;
        } catch (InstantiationException e) {
            throw new RuntimeException("传入的Map子类无法实例化，可能不存在无参构造方法！", e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("传入的Map子类无法实例化，可能是抽象类或接口！", e);
        }
    }

    public static <T> Map<T, T> asMap(T... t) {
        return asMap(HashMap.class, t);
    }

    public static <K, V> boolean compRuleMap(Map<K, V> map1, Map<K, V> map2, boolean compOrIgnore, K... keys) {
        if (null == map1 && null == map2) return true;
        else if (null == map1 || null == map2) return false;

        if (compOrIgnore) {
            for (K key : keys) {
                V value1 = map1.get(key);
                V value2 = map2.get(key);

                if (null == value1) {
                    if (null != value2) return false;
                    continue;
                } else if (null == value2) return false;

                if (!value1.equals(value2)) return false;
            }
        } else {
            for (Map.Entry<K, V> entry : map1.entrySet()) {
                K key = entry.getKey();

                List<K> props;

                if (null == keys) {
                    props = new ArrayList<>();
                } else {
                    props = new ArrayList<>(Arrays.asList(keys));
                }

                if (props.contains(key)) continue;

                V value1 = entry.getValue();
                V value2 = map2.get(key);

                if (null == value1) {
                    if (null != value2) return false;
                    continue;
                } else if (null == value2) return false;

                if (!value1.equals(value2)) return false;
            }
        }

        return true;
    }

    public static <K, V> boolean compRuleMap(Map<K, V> map1, Map<K, V> map2, K... keys) {
        if (null == keys) {
            return compRuleMap(map1, map2, false);
        }

        return compRuleMap(map1, map2, true, keys);
    }

    public static void main(String[] args) {
        Map map = MapUtil.asMap(HashMap.class);
        System.out.println(map);
        System.out.println(map.get(null));
    }
}
